<?php

/**
 * 培训控制器
 * @author yanghao <yh38615890@sina.cn>
 * @date 07-04-12
 * @copyright (c) gandianli
 */

namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use think\exception\HttpException;
use com\gdl\newagk\dataobject\invcode\InvcodeRequestDTO;
use com\gdl\newagk\dataobject\invcode\InvcodeDTO;
use com\gdl\newagk\interfaces\InvcodeServiceClient;

class Invcode extends Base
{


	//生成验证码与图片二维码
    public function generateCode() {
		$username = $this->request->param('username') ? $this->request->param('username') :  0;
		$reg = $this->request->param('reg') ? $this->request->param('reg') :  0;
		if(!$username || !$reg){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>['qrcode'=>'','base'=>'']];
			return json_encode($data);
		}
        try {
            //\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new InvcodeServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new InvcodeRequestDTO();
            $engprojectDo->username = $username;
			$engprojectDo->field = $reg;

            $result = $api->inback($engprojectDo);

			$add = self::erwei($username,$result->data[0]['code']);
	   
			$data =  ['msg'=>'生成成功','code'=>'200','data'=>['qrcode'=>$result->data[0]['code'],'base'=>$add]];
        } catch (Exception $ex) {
            $data = ['msg'=>'生成失败','code'=>'400','data'=>['qrcode'=>'','base'=>'']];
        }
        return json_encode($data);
    }
	
	
	//查询二维码
    public function lookeCode() {

		$reg = $this->request->param('reg') ? $this->request->param('reg') :  0;
		if(!$reg){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>['qrcode'=>'','base'=>'','status'=>0]];
			return json_encode($data);
		}
        try {
            //\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new InvcodeServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new InvcodeRequestDTO();
			$engprojectDo->field = $reg;

            $result = $api->lookeCode($engprojectDo);
			$qrCode = empty($result->data[0]['qrCode']) ? '' : $result->data[0]['qrCode'].'?r'.mt_rand(1,90000);
			$data =  ['msg'=>'查询成功','code'=>'200','data'=>['qrcode'=>$qrCode,'base'=>$result->data[0]['code'],'status'=>$result->data[0]['status']]];
        } catch (Exception $ex) {
            $data = ['msg'=>'查询失败','code'=>'400','data'=>['qrcode'=>'','base'=>'','status'=>0]];
        }
        return json_encode($data);
    }
	
	//保存/修改二维码
    public function saveCode() {
		$code = $this->request->post('code') ? $this->request->post('code') :  '';
		$imgurl = $this->request->post('imgurl') ? $this->request->post('imgurl') :  '';
		$reg = $this->request->post('reg') ? $this->request->post('reg') :  '';
		$status= $this->request->post('status') ? $this->request->post('status') :  3;
		if($code=='' || $reg==''){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
        try {
            //\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new InvcodeServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new InvcodeRequestDTO();
            $engprojectDo->filename['code'] = $code;
			$engprojectDo->filename['imgurl'] = $imgurl;
			$engprojectDo->filename['reg'] = $reg;
			$engprojectDo->filename['status'] = $status;
            $result = $api->saveCode($engprojectDo);

			if($result->code){
				$data =  ['msg'=>'保存成功','code'=>'200'];
			} else {
				$data = ['msg'=>$result->message,'code'=>'400'];
			}
        } catch (Exception $ex) {
            $data = ['msg'=>'保存失败','code'=>'400'];
        }
        return json_encode($data);
    }
	
	//根据自定义二维码生成图片二维码
    public function customizeCode() {
		$code = $this->request->param('code') ? $this->request->param('code') :  0;
		$username = $this->request->param('username') ? $this->request->param('username') :  0;
		if(!$code || !$username){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>['qrcode'=>'','base'=>'']];
			return json_encode($data);
		}
		
		if(strlen($code)<6){
			$data = ['msg'=>'生成失败，邀请码不能少于6位','code'=>'500','data'=>['qrcode'=>'','base'=>'']];
			return json_encode($data);
		}
        try {
			$add = self::erwei($username,$code);
			$data =  ['msg'=>'生成成功','code'=>'200','data'=>['base'=>$add]];
        } catch (Exception $ex) {
            $data = ['msg'=>'生成失败','code'=>'400','data'=>['base'=>'']];
        }
        return json_encode($data);
    }
	
	/**
     * 平台邀请码使用
     * @outputBuffering 
     * @param $code 
     */
    public function plaformInvitCode() 
    {
        $code = $this->request->param('code') ? getStr($this->request->param('code'), 'string') : '';
        $userid = $this->request->param('userid') ? getStr($this->request->param('userid'),'int') : 0;
		if(!$userid || !$code){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $plaformService = new InvcodeServiceClient(NULL);
            \ApiClient::build($plaformService);
			$engprojectDo = new InvcodeDTO();
            $engprojectDo->id = $userid;
			$engprojectDo->code = $code;
            $result = $plaformService->plaformInviteCodeConfirm($engprojectDo);
		
            if ($result->code) {
                $data = ['msg'=>'绑定成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，绑定失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	//平台列表
	 public function getPlaform()
    {
        $plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        $plaform = [];
        $userid = $this->request->param('userid') ? $this->request->param('userid') : '';
		$page = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
		$pagesize = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
		$title = $this->request->param('key') ? getStr($this->request->param('key'), 'string') : '';
		$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
		$filename['title'] = $title;
		$filename['status'] = $status;
		$filename['page'] = $page;
		$filename['pagesize'] = $pagesize;

		if(!$userid){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		$plaform_id = (int)$plaform_id;
            try {
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
                $UserService = new InvcodeServiceClient(NULL);
                \ApiClient::build($UserService);

                $result = $UserService->getPlaform($plaform_id, $filename, $userid, 1);

                if ($result->success == TRUE) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'查询成功','code'=>'200'];
                        $plaform['data'] = $result->data;
						$plaform['totalNumber'] =$result->message;
						
                    } else {
						$plaform = ['msg'=>'查询失败','code'=>'400'];
                        $plaform['data'] = [];
						$plaform['totalNumber'] =0;
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
					$plaform['totalNumber'] =0;
                    
                }
            } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[],'totalNumber'=>0];
            }
           
            return json_encode($plaform);
        
    }
	
	
	/**
     * 添加平台
     * @outputBuffering 
     * @param $code 
     */
    public function plaformAdd() 
    {
        if (!$this->request->isPost()) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$data = $this->request->post();
		$data['real'] = $data['name'];
		$PinYin= new \PinYin();
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $plaformService = new InvcodeServiceClient(NULL);
            \ApiClient::build($plaformService);
			$engprojectDo = new InvcodeRequestDTO();
            $engprojectDo->filename = $data;
			$engprojectDo->filename['name'] = $PinYin->getAllPY($data['real']);
            $result = $plaformService->plaformAdd($engprojectDo);
		
            if ($result->code) {
               $data = ['msg'=>'添加成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'添加失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，添加失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	
	/**
     * 查询设置好的平台信息
     * @outputBuffering 
     * @param $code 
     */
    public function plaformSelect() 
    {
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        if (!$plaform_id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		
		
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $plaformService = new InvcodeServiceClient(NULL);
            \ApiClient::build($plaformService);
			$engprojectDo = new InvcodeRequestDTO();

			$engprojectDo->plaform = $plaform_id;
            $result = $plaformService->plaformEdit($engprojectDo);

            if($result->code){
			$data = ['msg'=>'操作成功','code'=>'200','data'=>$result->data];
				
            } else {
               $data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	/**
     * 查询或修改平台
     * @outputBuffering 
     * @param $code 
     */
    public function plaformEdit() 
    {
        if (!$this->request->isPost() || empty($this->request->post('name'))) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		
		
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $plaformService = new InvcodeServiceClient(NULL);
            \ApiClient::build($plaformService);
			$engprojectDo = new InvcodeRequestDTO();
            $engprojectDo->filename = $this->request->post();
            $result = $plaformService->plaformEdit($engprojectDo);

            if ($result->code) {
				
					$data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
				
            } else {
               $data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	/**
     * 修改平台状态
     * @outputBuffering 
     * @param $code 
     */
    public function plaformStatus() 
    {
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        if (!$plaform_id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$filename = [];
		if($this->request->param('status')){
			$filename['status'] = $this->request->param('status') ? 1 : 3;
		} else if($this->request->param('isdelete')){
			$filename['isdelete'] = $this->request->param('del') ? 1 : 0;
		}
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $plaformService = new InvcodeServiceClient(NULL);
            \ApiClient::build($plaformService);
			$engprojectDo = new InvcodeRequestDTO();
            $engprojectDo->filename = $filename;
			$engprojectDo->plaform = $plaform_id;
            $result = $plaformService->plaformStatus($engprojectDo);
		
            if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	
	
	
	public function erwei($name=1,$url=''){
		Vendor('phpqrcode.phpqrcode');

        //生成二维码图片
        $object = new \QRcode();
        $level=3;
        $size=4;
        $errorCorrectionLevel =intval($level) ;//容错级别
        $matrixPointSize = intval($size);//生成图片大小
		$add = dirname(dirname(dirname(dirname(__FILE__)))).'/public/static/admin/erwei/'.$name.'.png';
        $object->png($url,$add, $errorCorrectionLevel, $matrixPointSize, 2);
		$addre ='http://'.$_SERVER['HTTP_HOST'].'/static/admin/erwei/'.$name.'.png';
		
		if(!file_exists($add)){
		/*	$base64_image_content = base64_encode(file_get_contents($add));
			$result = \Qiniu::instance()->uploadBase64Img($base64_image_content); //七牛上传
			$address = $result[0]['key'];
			$addre = Config::get('qiniu.QINIU_DOMAIN') . $address;*/
		}
		return  $addre;

	}

	
	

}
